const express = require("express");
const router = express.Router();
const bcrypt = require("bcryptjs");
const jwt = require("jsonwebtoken");
const { pool } = require("../config/db");
const logger = require("../utils/logger");

// 用户注册
router.post("/register", async (req, res) => {
  try {
    const { username, password } = req.body;

    // 验证输入
    if (!username || !password) {
      return res.status(400).json({ message: "用户名和密码不能为空" });
    }

    // 检查用户名是否已存在
    const [existingUsers] = await pool.query(
      "SELECT * FROM users WHERE username = ?",
      [username]
    );
    if (existingUsers.length > 0) {
      return res.status(400).json({ message: "用户名已存在" });
    }

    // 加密密码
    const salt = await bcrypt.genSalt(10);
    const hashedPassword = await bcrypt.hash(password, salt);

    // 创建新用户
    const [result] = await pool.query(
      "INSERT INTO users (username, password) VALUES (?, ?)",
      [username, hashedPassword]
    );

    // 生成JWT令牌
    const token = jwt.sign(
      { id: result.insertId, username },
      process.env.JWT_SECRET,
      { expiresIn: "24h" }
    );

    res.status(201).json({
      message: "用户注册成功",
      token,
      user: {
        id: result.insertId,
        username,
      },
    });
  } catch (error) {
    logger.error(`注册错误: ${error.message}`, { error: error.stack });
    res.status(500).json({ message: "服务器错误" });
  }
});

// 用户登录
router.post("/login", async (req, res) => {
  try {
    const { username, password } = req.body;

    // 验证输入
    if (!username || !password) {
      return res.status(400).json({ message: "用户名和密码不能为空" });
    }

    // 查找用户
    const [users] = await pool.query("SELECT * FROM users WHERE username = ?", [
      username,
    ]);
    if (users.length === 0) {
      return res.status(400).json({ message: "用户名或密码不正确" });
    }

    const user = users[0];

    // 验证密码
    const isMatch = await bcrypt.compare(password, user.password);
    if (!isMatch) {
      return res.status(400).json({ message: "用户名或密码不正确" });
    }

    // 生成JWT令牌
    const token = jwt.sign(
      { id: user.id, username: user.username },
      process.env.JWT_SECRET,
      { expiresIn: "24h" }
    );

    res.json({
      message: "登录成功",
      token,
      user: {
        id: user.id,
        username: user.username,
        wallet_address: user.wallet_address,
      },
    });
  } catch (error) {
    logger.error(`登录错误: ${error.message}`, { error: error.stack });
    res.status(500).json({ message: "服务器错误" });
  }
});

module.exports = router;
